<template>
  <div class="instrument-management">
    <el-card shadow="never">
      <div class="header" v-permission="['editInstrument']">
        <el-button type="primary" @click="showAddDialog">
          <el-icon><Plus /></el-icon>新增乐器
        </el-button>
      </div>
      
      <el-table :data="instruments" style="width: 100%">
        <el-table-column prop="name" label="乐器名称" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'">
              {{ row.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" v-permission="['editInstrument']">
          <template #default="{row}">
            <el-button size="small" @click="editInstrument(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteInstrument(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${mode === 'add' ? '新增' : '编辑'}乐器`"
      fullscreen
    >
      <el-form :model="form" ref="formRef" label-width="100px">
        <el-form-item label="乐器名称" prop="name" required>
          <el-input v-model="form.name" placeholder="请输入乐器名称" />
        </el-form-item>
        
        <el-form-item label="乐器状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">启用</el-radio>
            <el-radio value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="乐器描述" prop="description">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="form.description"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
              @onChange="handleChange"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, shallowRef, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { getToken} from '@/utils/auth'
import { 
  getInstrumentList,
  addInstrument,
  updateInstrument,
  deleteInstrument
} from '@/api/instrument'

const instruments = ref([])

// 对话框控制
const dialogVisible = ref(false)
const formRef = ref(null)
const mode = ref('add') // 'add' or 'edit'
const currentId = ref(null)

// 表单数据
const form = reactive({
  name: '',
  description: '',
  status: '1' // '1': 启用, '0': 禁用
})

// wangEditor
const editorRef = shallowRef(null)

// 编辑器配置
const editorConfig = {
  MENU_CONF: {
    uploadImage: {
      server: '/api/upload',
      fieldName: 'file',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      },
      allowedFileTypes: ['image/*'],
      onSuccess(file, res) {
        if (res.code !== 200) {
          ElMessage.error(res.message || '图片上传失败')
        }
      },
      customInsert(res, insertFn) {
        insertFn(res.data)
      }
    },
    uploadVideo: {
      server: '/api/upload',
      fieldName: 'file',
      headers: {
        'Authorization': `Bearer ${getToken()}`
      },
      allowedFileTypes: ['video/*'],
      onSuccess(file, res) {
        if (res.code !== 200) {
          ElMessage.error(res.message || '视频上传失败')
        }
      },
      customInsert(res, insertFn) {
        insertFn(res.data)
      }
    }
  },
  placeholder: '请输入乐器描述...',
  height: 600
}

const toolbarConfig = {}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  if (form.description) {
    editor.setHtml(form.description)
  }
}

const handleChange = (editor) => {
  form.description = editor.getHtml()
}

// 加载状态
const loading = ref(false)

// 获取乐器列表
const fetchInstruments = async () => {
  loading.value = true
  try {
    const res = await getInstrumentList()
    if (res.code === 200) {
      instruments.value = res.data.map(item => ({
        id: item.id,
        name: item.icName,
        description: item.description,
        status: item.status
      }))
    }
  } catch (error) {
    ElMessage.error('获取乐器列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  fetchInstruments()
})

// 显示新增对话框
const showAddDialog = () => {
  mode.value = 'add'
  form.name = ''
  form.description = ''
  dialogVisible.value = true
}

// 显示编辑对话框
const editInstrument = (row) => {
  mode.value = 'edit'
  currentId.value = row.id
  form.name = row.name
  form.description = row.description
  form.status = row.status
  dialogVisible.value = true
}

// 删除乐器
const handleDeleteInstrument = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除乐器 "${row.name}"?`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteInstrument({ids:row.id})
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await fetchInstruments()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除乐器失败:', error)
  }
}

// 提交表单
const submitForm = async () => {
  if (!form.name) {
    ElMessage.error('请输入乐器名称')
    return
  }

  try {
    let success
    if (mode.value === 'add') {
      console.log(form)
      success = await addInstrument(form)
    } else {
      success = await updateInstrument({
        ...form,
        id: currentId.value
      })
    }
    
    if (success) {
      ElMessage.success(mode.value === 'add' ? '新增成功' : '更新成功')
      dialogVisible.value = false
      await fetchInstruments()
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    console.log('提交表单失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}
</script>

<style scoped>
.instrument-management {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
.editor-container {
  border: 1px solid #ccc;
  z-index: 100;
}
.editor-toolbar {
  border-bottom: 1px solid #ccc;
}
.editor-text-container {
  height: 500px;
}
</style>
